from datetime import date, timedelta

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAdminUser

from goods_app.models import Category
from order_app.models import OrderInfo
from user_app.models import User


class UserCount(APIView):
    """
    返回注册的用户总数
    """
    permission_classes = [IsAdminUser]

    def get(self, request, *args, **kwargs):
        data = {'count': User.objects.all().count(), 'date': date.today()}
        return Response(data)


class IncrementUser(APIView):
    """
    返回当日新增用户数量
    """
    permission_classes = [IsAdminUser]

    def get(self, request, *args, **kwargs):
        now_tody = date.today()
        data = {}
        # 注册日期大于等于今天日期
        data.update(
            {'count': User.objects.filter(date_joined__gte=now_tody).count()})
        data.update({'date': now_tody})
        return Response(data)


class DayActiveUser(APIView):
    """
    日活跃用户数量
    """

    def get(self, request):
        now_today = date.today()
        data = {}
        data.update(
            {'count': User.objects.filter(last_login__gte=now_today).count()})
        data.update(({'date': now_today}))
        return Response(data)


class DayOrderUser(APIView):
    """
    日下单用户数量
    """

    def get(self, request):
        now_today = date.today()
        data = {}
        data.update(
            {"count": OrderInfo.objects.filter(
                create_time__gte=now_today).count()})
        data.update({"date": now_today})
        return Response(data)


class MonthIncrementUser(APIView):
    """
    月增用户统计
    """

    def get(self, *args, **kwargs):
        data = []
        now_today = date.today()
        # 获取一个月前的日期
        # 遍历每个日期 直到now
        # 比较 遍历到的日期-1   遍历到的日期+1 注册的用户数量

        start_month_day = now_today - timedelta(30)

        for i in range(30):
            start_month_day += timedelta(1)
            # front_month_day = start_month_day - timedelta(1)
            # tail_month_day = start_month_day + timedelta(1)

            count = User.objects.filter(date_joined__year=start_month_day.year,
                                        date_joined__month=start_month_day.month,
                                        date_joined__day=start_month_day.day).count()

            da = {}
            da.update({'count': count})
            da.update({'date': start_month_day})
            data.append(da)

        return Response(data)


class GoodsDayViewCount(APIView):
    """
    日商品分类访问数量
    """

    def get(self, request):
        now_today = date.today()
        data = []
        for cate in Category.objects.all():
            data.append({"category": cate.name,
                         "count": cate.visit_category.filter(
                             visit_time__gte=now_today).count()})

        return Response(data)
